//
//  CNM_ExString.swift
//  swiftTXH
//
//  Created by Mac mini on 2020/12/27.
//  Copyright © 2020 Mac mini. All rights reserved.
//

import UIKit

extension String {
    /// 根据多个字符分割字符串;
    /// public let strs = cc_separatedMore("12#34&ddd*99", characters: CharacterSet(["#","&","*"]))  ==> ["12", "34", "ddd", "99"]
    public func cnm_separatedMore(by characters: CharacterSet) -> Array<String>? {
        if !cnm_isBlank(self) {
            return self.components(separatedBy: characters)
        }
        return nil
    }

    /// 根据某个字符分割字符串;
    public func cnm_separated(separatedBy separated: String) -> Array<String>? {
        if !cnm_isBlank(self) {
            return self.components(separatedBy: separated)
        }
        return nil
    }
    
    /// 截取字符串：从起始处到index
    public func cnm_subStringTo(index toIndex: Int) -> String {
        // 选最小值，防止超出字符串最大长度
        let _endIndex = self.index(startIndex, offsetBy: min(self.count, toIndex))
        return String(self[startIndex..<_endIndex])
    }
    
    /// 截取字符串：从index处到结束处
    public func cnm_subStringFrom(index fromIndex: Int) -> String {
        // offsetBy: 负数 则往左移fromIndex; 正数：则往右移fromIndex
        let _startIndex = self.index(startIndex, offsetBy: min(self.count, fromIndex))
        return String(self[_startIndex..<endIndex])
    }
    
    /// 截取字符串：指定起始位和字符长度
    public func cnm_subString(_ begin: Int, length: Int) -> String {
        let start = self.index(self.startIndex, offsetBy: max(0, begin))
        let end = self.index(self.startIndex, offsetBy: min(self.count, begin + length))
        return String(self[start..<end])
    }
    
    /// 判断是否存在的某字符串
    public func cnm_contains(_ string: String) -> Bool {
        return self.contains(string)
    }
}
